package com.example.demo.domain.application;

import com.example.demo.domain.user.User;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.*;
import java.time.Instant;

/**
 * 应用开通记录
 * @author yingjianhua
 */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Setter
@Entity
public class OpenRecord {

    private OpenRecord(Application application, User user, String companyId, Scope scope) {
        this.scope = scope;
        this.user = user;
        if (companyId == null) {
            throw new RuntimeException("请选择要开通的公司");
        }
        this.companyId = companyId;
        this.application = application;
        this.openTime = Instant.now();
    }

    public static OpenRecord createCompanyScope(Application application, String companyId) {
        return new OpenRecord(application, null, companyId, Scope.Company);
    }

    public static OpenRecord createPersonScope(Application application, User user) {
        return new OpenRecord(application, user , user.getCompanyId(), Scope.Person);
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    /**
     * 开通范围
     */
    private Scope scope;
    /**
     * 应用
     */
    @ManyToOne
    private Application application;
    /**
     * 用户
     */
    @ManyToOne
    private User user;
    /**
     * 开通的公司id
     */
    private String companyId;
    /**
     * 开通时间
     */
    private Instant openTime;

    /**
     * 开通范围
     */
    public enum Scope {
        /**
         * 公司范围
         */
        Company,
        /**
         * 个人开通
         */
        Person
    }
}
